package babo.cd.physicalexperiment.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import babo.cd.physicalexperiment.data.UserInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;

import static java.lang.String.valueOf;

public class OkUtils {

    public static void GetOk(String url, Callback callback){
        OkHttpClient okHttpClient=new OkHttpClient();






        String jsessionId= UserInfo.JsessionId;
        if (TextUtils.isEmpty(jsessionId)){
            jsessionId="1";
        }
        url=URLS.HTTPHEAD+url;
        Out.out("请求URL=="+url);

        Request request = new Builder()
                .url(url)
                .addHeader("Cookie", "JSESSIONID="+jsessionId)
                .get()
                .build();
        if (okHttpClient==null){
            okHttpClient=new OkHttpClient();
        }
        Call call = okHttpClient.newCall(request);

        call.enqueue(callback);

    }
    public static void GetOkBacik(String url, Callback callback,String bacik){
        OkHttpClient okHttpClient=new OkHttpClient();
        url=URLS.HTTPHEAD+url;
        Out.out("获取地址："+url);
        Request request = new Builder()
                .url(url)
                .addHeader("Authorization", bacik)
                .get()
                .build();
        if (okHttpClient==null){
            okHttpClient=new OkHttpClient();
        }
        Call call = okHttpClient.newCall(request);

        call.enqueue(callback);

    }
    public static void postFile(OkHttpClient oo,final String url, final Map<String, String> map, File file,String keyww, Callback callback) {
        // form 表单形式上传
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (file != null) {
            // MediaType.parse() 里面是上传的文件类型。
            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            String filename = file.getName();
            // 参数分别为， 请求key ，文件名称 ， RequestBody
            requestBody.addFormDataPart(keyww, filename, body);
        }
        if (map != null) {
            // map 里面是请求中所需要的 key 和 value
            Set<Entry<String, String>> entries = map.entrySet();
            for (Entry entry : entries) {
                String key = valueOf(entry.getKey());
                String value = valueOf(entry.getValue());
                Log.d("HttpUtils", "key=="+key+"value=="+value);
                requestBody.addFormDataPart(key,value);
            }
        }

//    SharedPreferences sp2 = BaseActivity.context.getSharedPreferences(
//        MyApplication.LOGIN_INFO, 0);
//    String uid=sp2.getString("userid", "");
//
//    SharedPreferences sp =MyApplication.sp;
//    String rqd = sp.getString("rqd", "");
//
//    String rqd2 = sp.getString("access", "");
//
//    if(Utils.isNull(rqd2)){
//      rqd=MyApplication.rid;
//      rqd2=MyApplication.token;
//    }
        Request request = new Builder().url(url).post(requestBody.build())
//            .addHeader("UserClient-Version", MyApplication.verison)
//        .addHeader("app-type", "0")
//        .addHeader("userId", uid)
//        .addHeader("Request-ID", rqd)
//        .addHeader("accessToken", rqd2)
                .build();
        Call call = oo.newCall(request);
        call.enqueue(callback);
        // readTimeout("请求超时时间" , 时间单位);
//		okHttpClient.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(callback);

    }
    public static Builder NetMode(int type, RequestBody body) {
        if (type == 1) {
            return new Builder().method("DELETE", body);
        } else if (type == 2) {
            return new Builder().method("POST", body);
        } else if (type == 3) {
            return new Builder().method("GET", null);
        } else if (type == 4) {
            return new Builder().method("PUT", body);
        } else if (type == 5) {
            return new Builder().method("PATCH", body);
        } else {
            return new Builder().method("POST", body);
        }
    }
    /**
     * 执行普通的post请求，参数集合全部转为json
     *
     * @param
     * @param callback 回调接口
     */
    public static  void performByJson(final Context context, String mUrl, HashMap<Object, Object> hashMap, int perType, final Callback callback) {

        mUrl=URLS.HTTPHEAD+mUrl;
        OkHttpClient mClient=new OkHttpClient();
        String json = JsonUtil.getJsonStringByEntity(hashMap);
        Out.out("传过去的json=="+json);
        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);

        String utoken= UserInfo.JsessionId;
        if (TextUtils.isEmpty(utoken)){
            utoken="1";
        }
        Out.out("Cookie=="+"JSESSIONID= " + utoken);

        final Request request = NetMode(perType, body)
                .url(mUrl)
                .addHeader("Cookie", "JSESSIONID= " + utoken)
                .build();
        if (mClient==null){
            mClient=new OkHttpClient();
        }
        Call call = mClient.newCall(request);

        call.enqueue(callback);

    }
    /**
     * 执行普通的post请求，参数集合全部转为json
     *
     * @param
     * @param callback 回调接口
     */
    public static  void performByJson23(final Context context, String mUrl, String json, int perType, final Callback callback) {

        mUrl=URLS.HTTPHEAD+mUrl;
        OkHttpClient mClient=new OkHttpClient();

        Out.out("传过去的json=="+json);
        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);

        String utoken= UserInfo.JsessionId;
        if (TextUtils.isEmpty(utoken)){
            utoken="1";
        }
        Out.out("Cookie=="+"JSESSIONID= " + utoken);

        final Request request = NetMode(perType, body)
                .url(mUrl)
                .addHeader("Cookie", "JSESSIONID= " + utoken)
                .build();
        if (mClient==null){
            mClient=new OkHttpClient();
        }
        Call call = mClient.newCall(request);

        call.enqueue(callback);

    }

    /**
     * 执行普通的post请求，参数集合全部转为json
     *
     * @param
     * @param callback 回调接口
     */
    public static  void performByJsonArray(final Context context, String mUrl, LinkedHashMap<Object, Object> hashMap, int perType, final Callback callback) {

        String json = JsonUtil.getJsonStringByEntity(hashMap);
        OkHttpClient mClient=new OkHttpClient();

        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);


        String jsessionId=UserInfo.JsessionId;

         mUrl=URLS.HTTPHEAD+mUrl;
         Out.out("请求地址："+mUrl);
         Request request = null;
         if (TextUtils.isEmpty(jsessionId)){
             Out.out("走空");
             request= NetMode(perType, body)
                     .url(mUrl)
                     .build();
         }else{
             Out.out("走非空");
             request= NetMode(perType, body)
                     .url(mUrl)
                     .addHeader("Cookie", "JSESSIONID= " + jsessionId)
                     .build();
         }

        if (mClient==null){
            mClient=new OkHttpClient();
        }
        Call call = mClient.newCall(request);

        call.enqueue(callback);

//        mClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        netCallBack.onNetFailure();
//                    }
//                });
//                doFailure(netCallBack);
//            }
//
//            @Override
//            public void onResponse(Call call, final Response response) throws IOException {
//                doResponse(head, context, response, netCallBack);
//            }
//        });
    }
}
